package org.darcy.service.check.impl;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.darcy.dao.CheckCollectMapper;
import org.darcy.entity.CheckCollect;
import org.darcy.entity.CheckDelivery;
import org.darcy.entity.CheckLibAnalysis;
import org.darcy.entity.work.WorkInstance;
import org.darcy.framework.constant.SysConstant;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.framework.model.PageData;
import org.darcy.framework.model.PageParam;
import org.darcy.service.check.CheckCollectService;
import org.darcy.service.check.CheckDeliveryService;
import org.darcy.service.check.CheckLibAnalysisService;
import org.darcy.service.sys.SysFileService;
import org.darcy.service.work.WorkService;
import org.darcy.service.work.WorkTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.hutool.core.util.StrUtil;

/**
 * CheckCollect服务实现
 */
@Service
public class CheckCollectServiceImpl extends GenericServiceImpl<CheckCollect> implements CheckCollectService {

	@Autowired
	private CheckCollectMapper mapper;

	@Autowired
	private CheckDeliveryService CheckDeliveryService;

	@Autowired
	@Lazy
	private CheckLibAnalysisService CheckLibAnalysisService;

	@Autowired
	private WorkService WorkService;

	@Autowired
	private WorkTaskService WorkTaskService;

	@Autowired
	@Lazy
	private SysFileService SysFileService;

	/**
	 * 处理工作任务
	 */
	private void processWork(CheckCollect record) {
		// 生成审批任务
		WorkService.addWorkTask(record, null, null, record.getFormType());
	}

	@Override
	public CheckCollect getDetail(Integer id) {
		CheckCollect record = mapper.selectById(id);
		CheckDelivery CheckDelivery = CheckDeliveryService.getDetail(record.getDeliveryId());
		record.setDelivery(CheckDelivery);
		// 文件处理
		if (StrUtil.isNotEmpty(record.getCollectResult())) {
			record.setCollectResultList(SysFileService.getFilePathList(record.getCollectResult()));
		}
		if (StrUtil.isNotEmpty(record.getLibReport())) {
			record.setLibReportList(SysFileService.getFilePathList(record.getLibReport()));
		}

		return record;
	}

	@Override
	public PageData<CheckCollect> page(PageParam<CheckCollect> param) {
		PageData<CheckCollect> data = super.getPageData(param);
		return data;
	}

	@Override
	public List<CheckCollect> getList(Integer deliveryId, Boolean filter) {
		QueryWrapper<CheckCollect> q = new QueryWrapper<CheckCollect>();
		q.eq("delivery_id", deliveryId);
		if (filter) {
			q.isNull("pid");
		}
		return this.getList(q);
	}

	/**
	 * 处理附件
	 */
	private void processData(CheckCollect record) {
		// 处理附件
		if (record.getCollectResultList() != null && !record.getCollectResultList().isEmpty()) {
			String file = SysFileService.getFileIdList(record.getCollectResultList());
			record.setCollectResult(file);
		}
		if (record.getLibReportList() != null && !record.getLibReportList().isEmpty()) {
			String file = SysFileService.getFileIdList(record.getLibReportList());
			record.setLibReport(file);
		}
		CheckDelivery delivery = record.getDelivery();
		if (delivery != null) {
			if (delivery.getReportFileList() != null && !delivery.getReportFileList().isEmpty()) {
				String file = SysFileService.getFileIdList(delivery.getReportFileList());
				delivery.setReportFile(file);
			}
			if (delivery.getPublishPicList() != null && !delivery.getPublishPicList().isEmpty()) {
				String file = SysFileService.getFileIdList(delivery.getPublishPicList());
				delivery.setPublishPic(file);
			}
			if (delivery.getArchiveFileList() != null && !delivery.getArchiveFileList().isEmpty()) {
				String file = SysFileService.getFileIdList(delivery.getArchiveFileList());
				delivery.setArchiveFile(file);
			}
		}
	}

	@Override
	public CheckCollect updateFlow(CheckCollect record) {
		// 实验派工处理
		if (record.getFormType().equals(SysConstant.FormType.LibDispatch)) {
			List<CheckLibAnalysis> libAnalysisList = record.getLibAnalysisList();
			List<CheckLibAnalysis> libAnalysisListExist = CheckLibAnalysisService.getList(record.getId());
			for (CheckLibAnalysis a : libAnalysisList) {
				boolean exist = false;
				for (CheckLibAnalysis b : libAnalysisListExist) {
					if (a.getManager().equals(b.getManager())) {
						exist = true;
					}
				}
				if (exist) {
					continue;
				}
				a.setCheckId(record.getId());
				if (a.getId() == null)
					CheckLibAnalysisService.insert(a);
				else
					CheckLibAnalysisService.update(a);
			}
		}
		processData(record);
		// 采样办公室，归档，报告编制，公示
		CheckDelivery delivery = record.getDelivery();
		if (record.getFormType().equals(SysConstant.FormType.CheckCaiYangDept)
				|| record.getFormType().equals(SysConstant.FormType.Archive)
				|| record.getFormType().equals(SysConstant.FormType.CheckReport)
				|| record.getFormType().equals(SysConstant.FormType.ShowPublic)) {
			CheckDeliveryService.update(delivery);
		} else {
			super.update(record);
		}
		// 场调更新采样接收部门
		if (delivery != null && delivery.getSurveyAccept() != null) {
			CheckDeliveryService.update(delivery);
		}

		processWork(record);

		return record;
	}

	/**
	 * 处理采样列表，分为服务列表和次数列表
	 * 
	 */
	private void processCollectList(CheckCollect record) {
		List<CheckCollect> list = this.getList(record.getDeliveryId(), false);
		// 采样服务列表
		List<CheckCollect> collectServiceList = null;
		// 采样次数列表
		List<CheckCollect> collectJobList = null;
		Integer pid = record.getPid() != null ? record.getPid() : record.getId();
		collectServiceList = list.stream().filter(a -> a.getPid() == null).collect(Collectors.toList());
		collectJobList = list.stream().filter(a -> a.getPid() == pid).collect(Collectors.toList());
		if (record.getPid() != null) {
			CheckCollect root = list.stream().filter(a -> a.getId() == record.getPid()).findFirst().get();
			collectJobList.add(0, root.clone());
		} else {
			collectJobList.add(0, record.clone());
		}
		// 判断是不是多次采样
		Optional<CheckCollect> finished = collectJobList.stream()
				.filter(a -> Integer.valueOf(0).equals(a.getCollectFinished())).findFirst();
		if (finished.isPresent()) {
			record.setMultiple(true);
		} else {
			record.setMultiple(false);
		}
		CheckDelivery CheckDelivery = record.getDelivery();
		CheckDelivery.setCollectList(collectServiceList);
		record.setDelivery(CheckDelivery);
		record.setCollectList(collectJobList);
	}

	@Override
	public CheckCollect getDetailProgress(Integer id, String formType) {
		CheckCollect data = this.getDetail(id);
		processCollectList(data);
		// 收样，过滤不采样的数据
		if (formType.equals(SysConstant.FormType.CheckShouYang)) {
			List<CheckCollect> collectJobList = data.getCollectList().stream()
					.filter(a -> (a.getCollectFinished() != null && a.getCollectFinished() >= 0))
					.collect(Collectors.toList());
			data.setCollectList(collectJobList);
		}
		// 实验报告，增加进度信息
		if (formType.equals(SysConstant.FormType.LibDispatch) || formType.equals(SysConstant.FormType.LibAnalysis)
				|| formType.equals(SysConstant.FormType.LibReport)) {

			List<CheckLibAnalysis> libAnalysisList = CheckLibAnalysisService.getList(id);
			data.setLibAnalysisList(libAnalysisList);
			// 实验分析，指定
			if (formType.equals(SysConstant.FormType.LibAnalysis)) {
				List<CheckCollect> collectServiceList = data.getDelivery().getCollectList();

			}
			if (formType.equals(SysConstant.FormType.LibReport)) {
				// 进度信息
				StringBuffer s = new StringBuffer();
				boolean libFinished = true;
				for (CheckLibAnalysis a : libAnalysisList) {
					WorkInstance param = WorkInstance.builder().formType(SysConstant.FormType.LibAnalysis)
							.formId(a.getId()).build();
					WorkInstance work = WorkService.getBusinessWork(param);
					if (work == null) {
						libFinished = false;
						continue;
					}
					s.append(work.getTitle());
					if (work.getStatus().equals(SysConstant.FlowStatus.STATUS100_APPROVED)) {
						s.append("：审批通过");
					} else {
						s.append("：处理中");
					}
					s.append("\n");
				}
				data.setLibFinished(libFinished);
				data.setLibProgress(s.toString());
			}
		}
		return data;
	}

}
